package io.github.talelin.latticy.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

/**
 * @author lms
 * @date 2021/3/22 22:56
 * @description
 */
public class AesUtils {

    /**
     * 解密方法
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    public static String decryptWeChatRunInfo(String sessionKey, String encryptedData, String iv) {
        String result = null;
        //被加密的数据
        byte[] encrypData = Base64.decodeBase64(encryptedData);
        //偏移量
        byte[] ivData = Base64.decodeBase64(iv);
        //加密密钥
        byte[] sessionKeyB = Base64.decodeBase64(sessionKey);

        try {
            // 如果密钥不足16位，那么就补足
            int base = 16;
            if (sessionKeyB.length % base != 0) {
                int groups = sessionKeyB.length / base + (sessionKeyB.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(sessionKeyB, 0, temp, 0, sessionKeyB.length);
                sessionKeyB = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");

            SecretKeySpec spec = new SecretKeySpec(sessionKeyB, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivData));

            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(encrypData);
            if (null != resultByte && resultByte.length > 0) {
                result = new String(resultByte, "UTF-8");
                System.out.println("AESUtils中result:"+result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;



    }
}
